package com.fun.feifun.database;

import java.io.InputStream;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * jdbc 的工具类
 *
 */
public class JdbcUtils {

	private static String driver = null;
	private static String url = null;
	private static String username = null;
	private static String password = null;

	//    static{
	//        try{
	//            InputStream in = JdbcUtils.class.getClassLoader().getResourceAsStream("db.properties");
	//            Properties prop = new Properties();
	//            prop.load(in);
	//
	//            driver = prop.getProperty("driver");
	//            url = prop.getProperty("url");
	//            username = prop.getProperty("username");
	//            password = prop.getProperty("password");
	//
	//            Class.forName(driver);
	//
	//        }catch (Exception e) {
	//            throw new ExceptionInInitializerError(e);
	//        }
	//    }

	/**
	 * 获取数据库链接
	 * @param url 链接地址
	 * @param username 用户名
	 * @param password 密码
	 * @return
	 * @throws SQLException
	 */
	public static Connection getConnection(String url,
			String username,
			String password) throws SQLException {
		return DriverManager.getConnection(url, username,password);
	}


	/**
	 * 释放链接
	 * @param conn  链接点
	 * @param st    声明
	 * @param rs    结果集
	 */
	public static void release(Connection conn, Statement st, ResultSet rs){
		if(rs!=null){
			try{
				rs.close();
			}catch (Exception e) {
				e.printStackTrace();
			}
			rs = null;

		}
		if(st!=null){
			try{
				st.close();
			}catch (Exception e) {
				e.printStackTrace();
			}

		}
		if(conn!=null){
			try{
				conn.close();
			}catch (Exception e) {
				e.printStackTrace();
			}

		}

	}


	public static List<String> getTable(Connection conn) {
		//获取表名的结果集
		ResultSet rs = null;
		List<String> tableList= new ArrayList<>();
		try {
			DatabaseMetaData metaData = conn.getMetaData();
			rs=metaData.getTables(conn.getCatalog(), "%", "%",new String[]{"TABLE"});
			while(rs.next()){
				String tableName = rs.getString(3);
				tableList.add(tableName);
				System.out.println(tableName);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return tableList;
	}
}
